﻿using JunQuanPrinter.DB;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Speech.Synthesis; //用于语音朗读
using System.Speech.Recognition;//用于识别语音
using System.IO;

namespace JunQuanPrinter
{
    public partial class frmMain : Form
    {
        private CConfig m_Config = CConfig.getClass();
        private CDataParam m_DB = CDataParam.getClass();
        private TPmParamData m_PmParamData = new TPmParamData();


        public frmMain()
        {
            InitializeComponent();
        }

        private void tsMenuLoad_Click(object sender, EventArgs e)
        {
            frmLoadFile frm = frmLoadFile.getClass();
            frm.ShowDialog();
            frmLoadFile.CloseForm();
        }

        private void tsCommSet_Click(object sender, EventArgs e)
        {
            frmComPort frm = frmComPort.getClass();
            frm.ShowDialog();
            frmComPort.CloseForm();
        }

        private void frmMain_Shown(object sender, EventArgs e)
        {
            InitData();
            TopMost = true;
        }

        private void edtProNo_MouseLeave(object sender, EventArgs e)
        {
            
        }

        private void InitData()
        {
            try
            {
                edtProNo.Text = CConfigDB.getClass().getValue(CConfigDB.C_idx_LastProNo);
                cmbLineNum.Text = CConfigDB.getClass().getValue(CConfigDB.C_idx_LastLineNum);                
                edtIntervel.Text = CConfigDB.getClass().getValue(CConfigDB.C_idx_Inteval);

                chkFontFx.Checked = CConfigDB.getClass().getValue(CConfigDB.C_idx_Font_Fx).Equals("1");             
            }
            catch(Exception ex)
            {
                CTool.ShowMsgErr(ex.Message);
            }
        }

        private void cmbLineNum_DropDown(object sender, EventArgs e)
        {
            try
            {
                cmbLineNum.Items.Clear();
                String ProductCode = edtProNo.Text.Trim();
                if (ProductCode.Equals(""))
                    return;

                String[] lstName = CDataParam.getClass().getLineNums(ProductCode);
                foreach (String sName in lstName)
                {
                    cmbLineNum.Items.Add(sName);
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }

        }

        private void cmbLineNum_TextChanged(object sender, EventArgs e)
        {
            try
            {
                cmbSplit.Text = "";              
                edtContent.Text = "";
                edtContent1.Text = "";
                edtContent2.Text = "";
                cmbFont.Text = "";
                TDataParam data = m_DB.getData(edtProNo.Text.Trim(), cmbLineNum.Text.Trim());
                if (data.id == 0)
                    return;
                cmbSplit.Text = data.SPLIT;
                cmbFont.Text = data.Font;
                edtWireLen.Text = data.WIRE_LEN;
                edtStartPos.Text = data.START_POS;
                edtContent.Text = data.WORD_A;
                edtContent1.Text = data.WORD_B;
                edtContent2.Text = data.WORD_C;
                cmbFontSize.Text = data.FontSize;

            }
            catch(Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }


        /// <summary>
        /// 保存数据
        /// </summary>
        private Boolean SaveData()
        {
            try
            {
                Boolean blnIns = false;
                if (edtProNo.Text.Trim().Equals("")
                    || cmbLineNum.Text.Trim().Equals("")
                    || cmbSplit.Text.Trim().Equals("")
                    || cmbFont.Text.Trim().Equals("")
                    || edtIntervel.Text.Trim().Equals("")
                    || edtContent.Text.Trim().Equals("")
                    || cmbFontSize.Text.Trim().Equals("")
                    || edtWireLen.Text.Trim().Equals("")
                    || edtStartPos.Text.Trim().Equals(""))
                    //|| edtConnectPos.Text.Trim().Equals("")
                {
                    CTool.ShowMsgW("请将数据填写完整！");
                    return false;
                }
                TDataParam data = m_DB.getData(edtProNo.Text.Trim(), cmbLineNum.Text.Trim());
                if (data.id == 0)
                {
                    data.PRODUCT_CODE = edtProNo.Text.Trim();
                    data.LINE_NUM = cmbLineNum.Text.Trim();
                    blnIns = true;
                }

                data.SPLIT = cmbSplit.Text.Trim();
                data.Font = cmbFont.Text.Trim();
                data.WIRE_LEN = edtWireLen.Text.Trim();
                data.START_POS = edtStartPos.Text.Trim();
                data.WORD_A = edtContent.Text.Trim();
                data.WORD_B = edtContent1.Text.Trim();
                data.WORD_C = edtContent2.Text.Trim();
                data.PRINT_SPEED = "4960";
                data.TIME_DELAY = "3";
                data.FontSize = cmbFontSize.Text.Trim();


                if (blnIns)
                {
                    m_DB.Add(data);
                }
                else
                {
                    m_DB.Upd(data);
                }

                CConfigDB.getClass().Upd(CConfigDB.C_idx_LastProNo, edtProNo.Text);
                CConfigDB.getClass().Upd(CConfigDB.C_idx_LastLineNum, cmbLineNum.Text);
                CConfigDB.getClass().Upd(CConfigDB.C_idx_Inteval, edtIntervel.Text);
                if(chkFontFx.Checked)
                {
                    CConfigDB.getClass().Upd(CConfigDB.C_idx_Font_Fx, "1");
                }
                else
                {
                    CConfigDB.getClass().Upd(CConfigDB.C_idx_Font_Fx, "0");
                }
         

                return true;
            }
            catch(Exception ex)
            {
                CTool.ShowMsgErr(ex.Message);
                return false;
            }

        }

        private void btnSave_Click(object sender, EventArgs e)
        {
            try
            {

                if (!SaveData())
                    return;

                CTool.ShowMsg("保存数据成功");               

            }
            catch(Exception ex)
            {
                CTool.ShowMsgErr(ex.Message);
            }
        }

       

        private void SendData()
        {
            CCommad command = CCommad.getClass();
            //if(command.getCommSerial() ==null)
            //{
            //    CTool.ShowMsgW("当前串口未打开!");
            //    return;
            //}
            UInt16 interval = Convert.ToUInt16(edtIntervel.Text);
            Byte FontSize = Convert.ToByte(cmbFontSize.Text);
            UInt16 speed = Convert.ToUInt16(edtSpeed.Text);
            UInt16 wireLen = Convert.ToUInt16(edtWireLen.Text);
            UInt16 startLen = Convert.ToUInt16(edtStartPos.Text);
            UInt16 endSpace = 15;
            UInt16 tachoDiv = Convert.ToUInt16(cmbSplit.Text);
            if (!command.SendCMD_9B(edtContent.Text, edtContent1.Text, edtContent2.Text, tachoDiv, cmbFont.Text, FontSize,interval, endSpace, wireLen, startLen, speed, chkFontFx.Checked))
            {
                ShowStatus("接收数据超时！");
                CTool.ShowMsgErr("接收数据超时！");
                return ;
                    
            }

            ShowStatus("数据发送成功,调用任务...");

            if (!command.SendCMD_98())
            {
                ShowStatus("调用任务失败！");
                CTool.ShowMsgErr("调用任务失败！");
                return;
            }

            ShowStatus("调用任务成功...");
            CTool.ShowMsg("调用任务成功！");
        }

        private void TestSpeak()
        {
            Console.WriteLine("请输入中英文：");
            string s = Console.ReadLine();
            SpeechSynthesizer synth = new SpeechSynthesizer();
            //选择不同的发音
            synth.SelectVoice("Microsoft Anna");//美式发音，但只能读英文
            //synth.SelectVoice("Microsoft Lily");//能读中英文
            synth.Speak(s);
        }

        private void DownLoad()
        {
            try
            {
                if (!SaveData())
                    return;

                ShowStatus("下载成功,开始发送数据...");

                btnDown.Enabled = false;
                btnSave.Enabled = false;
                SendData();
            }
            catch (Exception ex)
            {
                CTool.ShowMsgErr(ex.Message);

            }
            finally
            {
                btnDown.Enabled = true;
                btnSave.Enabled = true;
            }
        }


        private void btnDown_Click(object sender, EventArgs e)
        {

            DownLoad();
        }

        private void frmMain_Load(object sender, EventArgs e)
        {
            int x = SystemInformation.PrimaryMonitorSize.Width - this.Width;
            int y = SystemInformation.PrimaryMonitorSize.Height/2 - this.Height/2;//要让窗体往上走 只需改变 Y的坐标
            this.Location = new Point(x, y);
        }

        private void frmMain_FormClosed(object sender, FormClosedEventArgs e)
        {
            if(CCommad.getClass().getCommSerial() != null)
            {
                CCommad.getClass().getCommSerial().Close();
            }
        }

        private void ShowStatus(String sHint)
        {
            toolStripStatusLabel1.Text = sHint;
            Application.DoEvents();
        }

        private void toolStripStatusLabel2_Click(object sender, EventArgs e)
        {

        }

        private void cmbFont_SelectedIndexChanged(object sender, EventArgs e)
        {
            if(cmbFont.SelectedIndex == 0)
            {
                edtSpeed.Text = "4960";
            }
            else
            {
                edtSpeed.Text = "3000";
            }
        }

        private void tsMnQry_Click(object sender, EventArgs e)
        {
            frmQry frm = frmQry.getClass();
            frm.ShowDialog();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            
        }

        private void tsLockFace_Click(object sender, EventArgs e)
        {
            TopMost = !TopMost;
            if(TopMost)
            {
                tsLockFace.Text = "取消锁定";
            }
            else
            {
                tsLockFace.Text = "锁定界面";
            }
        }

        public void Read()
        {
            try
            {
                Byte[] byData = new Byte[100];
                String filePath = "d:\\print.txt";
                string temp;
                string[] tempArr;
                FileStream file = new FileStream(filePath, FileMode.Open);
                if (file != null)
                {
                    file.Seek(0, SeekOrigin.Begin);                    
                    file.Read(byData, 0, 100); //byData传进来的字节数组,用以接受FileStream对象中的数据,第2个参数是字节数组中开始写入数据的位置,它通常是0,表示从数组的开端文件中向数组写数据,最后一个参数规定从文件读多少字符.
                    Decoder d = Encoding.Default.GetDecoder();                    
                    temp = Encoding.ASCII.GetString(byData);
                    tempArr = temp.Split(new[] {' '}, StringSplitOptions.RemoveEmptyEntries);
                    edtContent.Text = tempArr[0];
                    edtContent1.Text = tempArr[1];
                    if (tempArr.Length>2)
                    {
                        edtContent2.Text = tempArr[2];
                    }
                    
                    //d.GetChars(byData, 0, byData.Length, charData, 0);
                    //Console.WriteLine(charData);
                    file.Close();
                    System.IO.File.Delete(filePath);

                    DownLoad();
                }

                
            }
            catch (IOException e)
            {
                Console.WriteLine(e.ToString());
            }
        }

        private void timer1_Tick(object sender, EventArgs e)
        {
            Read();
            Application.DoEvents();
        }
    }
}
